package handlers

import (
	"context"
	"ourplansystem/server/ent"
	"ourplansystem/server/ent/mediarecord"
	"ourplansystem/server/models"
	"strconv"
	"time"

	"github.com/gofiber/fiber/v2"
)

// MediaRecordHandler 书影音记录处理器
type MediaRecordHandler struct {
	client *ent.Client
}

// NewMediaRecordHandler 创建书影音记录处理器
func NewMediaRecordHandler(client *ent.Client) *MediaRecordHandler {
	return &MediaRecordHandler{client: client}
}

// CreateMediaRecordRequest 创建书影音记录请求
type CreateMediaRecordRequest struct {
	Title     string `json:"title"`
	Type      string `json:"type"` // 电影/书/音乐
	Status    string `json:"status"`
	Rating    int32  `json:"rating"`
	Note      string `json:"note"`
	CreatorID int64  `json:"creator_id"`
}

// UpdateMediaRecordRequest 更新书影音记录请求
type UpdateMediaRecordRequest struct {
	Title  string `json:"title"`
	Status string `json:"status"`
	Rating int32  `json:"rating"`
	Note   string `json:"note"`
}

// GetMediaRecords 获取所有未删除的书影音记录
func (h *MediaRecordHandler) GetMediaRecords(c *fiber.Ctx) error {
	ctx := context.Background()
	mediaRecords, err := h.client.MediaRecord.Query().
		Where(mediarecord.DeletedAtIsNil()).
		WithCreator().
		All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取书影音记录失败")
	}

	return models.Success(c, mediaRecords)
}

// GetMediaRecord 获取单个书影音记录
func (h *MediaRecordHandler) GetMediaRecord(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的记录ID")
	}

	mediaRecord, err := h.client.MediaRecord.Get(ctx, id)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "记录不存在")
		}
		return models.InternalServerError(c, "获取记录失败")
	}

	return models.Success(c, mediaRecord)
}

// CreateMediaRecord 创建书影音记录
func (h *MediaRecordHandler) CreateMediaRecord(c *fiber.Ctx) error {
	ctx := context.Background()
	var req CreateMediaRecordRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	if req.Title == "" {
		return models.BadRequest(c, "标题不能为空")
	}

	if req.Type == "" {
		return models.BadRequest(c, "类型不能为空")
	}

	if req.CreatorID == 0 {
		return models.BadRequest(c, "创建者ID不能为空")
	}

	builder := h.client.MediaRecord.
		Create().
		SetTitle(req.Title).
		SetType(req.Type).
		SetCreatorID(req.CreatorID)

	if req.Status != "" {
		builder.SetStatus(req.Status)
	}

	if req.Rating > 0 {
		builder.SetRating(req.Rating)
	}

	if req.Note != "" {
		builder.SetNote(req.Note)
	}

	mediaRecord, err := builder.Save(ctx)
	if err != nil {
		return models.InternalServerError(c, "创建记录失败")
	}

	return models.SuccessWithMessage(c, "创建成功", mediaRecord)
}

// UpdateMediaRecord 更新书影音记录
func (h *MediaRecordHandler) UpdateMediaRecord(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的记录ID")
	}

	var req UpdateMediaRecordRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	builder := h.client.MediaRecord.UpdateOneID(id)

	if req.Title != "" {
		builder.SetTitle(req.Title)
	}

	if req.Status != "" {
		builder.SetStatus(req.Status)
	}

	if req.Rating > 0 {
		builder.SetRating(req.Rating)
	}

	if req.Note != "" {
		builder.SetNote(req.Note)
	}

	mediaRecord, err := builder.Save(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "记录不存在")
		}
		return models.InternalServerError(c, "更新记录失败")
	}

	return models.SuccessWithMessage(c, "更新成功", mediaRecord)
}

// DeleteMediaRecord 软删除书影音记录
func (h *MediaRecordHandler) DeleteMediaRecord(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的记录ID")
	}

	// 软删除：设置 deleted_at 为当前时间
	now := time.Now()
	_, err = h.client.MediaRecord.UpdateOneID(id).
		SetDeletedAt(now).
		Save(ctx)

	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "记录不存在")
		}
		return models.InternalServerError(c, "删除记录失败")
	}

	return models.SuccessWithMessage(c, "删除成功", nil)
}

// GetDeletedMediaRecords 获取所有已删除的书影音记录（回收站）
func (h *MediaRecordHandler) GetDeletedMediaRecords(c *fiber.Ctx) error {
	ctx := context.Background()
	mediaRecords, err := h.client.MediaRecord.Query().
		Where(mediarecord.DeletedAtNotNil()).
		WithCreator().
		All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取已删除书影音记录失败")
	}

	return models.Success(c, mediaRecords)
}

// RestoreMediaRecord 恢复已删除的书影音记录
func (h *MediaRecordHandler) RestoreMediaRecord(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的记录ID")
	}

	// 恢复：清空 deleted_at
	_, err = h.client.MediaRecord.UpdateOneID(id).
		ClearDeletedAt().
		Save(ctx)

	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "记录不存在")
		}
		return models.InternalServerError(c, "恢复书影音记录失败")
	}

	return models.SuccessWithMessage(c, "恢复成功", nil)
}

// PermanentDeleteMediaRecord 永久删除书影音记录
func (h *MediaRecordHandler) PermanentDeleteMediaRecord(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的记录ID")
	}

	err = h.client.MediaRecord.DeleteOneID(id).Exec(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "记录不存在")
		}
		return models.InternalServerError(c, "永久删除书影音记录失败")
	}

	return models.SuccessWithMessage(c, "永久删除成功", nil)
}
